const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
const {
  randomNum
} = require('../../utils/util.js');
const manage = wx.getBackgroundAudioManager()
const SEQUENCE_MODE = 1
const RANDOM_MOD = 2
const SINGLE_CYCLE_MOD = 3

Page({
  data: {
    title: '栏目',
    Ttitle:'',
    bgimg: '',
    categoryId: '',
    categorydata: '',
    sortBy: 3,
    audioListdata: [],
    page: 1,
    pageSize: 10,
    isEnd: false,
    iscollect: false,
    Collectid: 0,

    playurl: '',
    currentSong: null,
    playMod: 1,
    isloading:true,

  },
  onLoad: function (options) {
    console.log(options)
    if (options && options.id) {
      this.setData({
        categoryId: options.id,
        Ttitle: options.title,
        bgimg: options.img
      })
      this.audioList()
      this.categoryDetail()

    }
    if(options.scene){
        const id = decodeURIComponent(options.scene);
        console.log(id)
        this.setData({
          categoryId: id
        })
        this.categoryDetail()
        this.audioList()
      }
  },
  audioList() {
    Controller.audioList({
      categoryId: this.data.categoryId,
      sortBy: this.data.sortBy,
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.data.baseData.list.length > 0) {
        this.setData({
          audioListdata: res.data.baseData.list
        })
        if (res.data.baseData.lastPage) {
          this.setData({
            isEnd: true
          })
        }
      }
      this.setData({isloading:false})
    }).catch(res=>{
      this.setData({isloading:false})
    })
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    if (e.scrollTop > 20) {
      this.setData({
        defaultFix: true
      })
    } else {
      this.setData({
        defaultFix: false
      })
    }
  },
  scrollend() {
    if (this.data.isEnd) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      this.audioList()
    }
  },
  descmore() {
    let that = this
    that.Dialog.ShowDialog({
      title: that.data.categorydata.title,
      content:that.data.categorydata.desc,
      type: 'BottomAlert',
      callback(obj) {
        that.Dialog.CloseDialog();
      }
    })
  },
  playall(e) {
    var index=0;
    if(e.currentTarget.dataset.index){
      index=e.currentTarget.dataset.index
    }
    app.globalData.currentIndex=index
    app.globalData.songlist=this.data.audioListdata
    // this._init()

    wx.navigateTo({
      url: "/pages/Playing/Playing?categoryId=" + this.data.categoryId + "&sortBy=" +this.data.sortBy  + "&currentIndex=" + index
    })
  },
  categoryDetail() {
    Controller.categoryDetail({
      categoryId: this.data.categoryId
    }).then(res => {
      this.setData({
        categorydata: res.data.baseData
      })
      this.checkCollect()
    })
  },
  comments(e) {
    app.comments(this.data.categorydata.id, 1)
  },
  share(e) {
    app.share(this.data.categorydata.id, 1,this.data.categorydata.title,this.data.categorydata.imgUrl)
  },
  collect(e) {
    if (!wx.getStorageSync('logintoken')) {
      this.ToLogin()
    }else{
      let data = {
        rid: this.data.categorydata.id || '',
        type: 1,
        bodyId:2
      }
      
      Controller.collect(data).then(res => {
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 1500
        })
        this.checkCollect()
        app.updateScore(9)
      })
    }
    
  },
  checkCollect() {
    Controller.checkCollect({
      rid: this.data.categorydata.id,
      type: 1
    }).then(res => {
      if (res.data.baseData) {
        this.setData({
          iscollect: true,
          Collectid: res.data.baseData
        })
      } else {
        this.setData({
          iscollect: false
        })
      }
    })
  },
  delcollect(e) {
    // 取消收藏
    var that=this;
    if (!wx.getStorageSync('logintoken')) {
      that.ToLogin()
    }else{
      console.log('用户取消收藏接口')
      wx.showModal({
        title: '提示',
        content: '是否取消收藏?',
        success(res) {
          if (res.confirm) {
            Controller.delCollect({
              ids: that.data.Collectid
            }).then(res => {
              that.checkCollect()
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    
  },
  onReady() {
    this.Dialog = this.selectComponent('#Dialog');
  },
  download(e) {
    let that = this

    that.Dialog.ShowDialog({
      title: '是否下载音频',
      type: 'Confirm',
      callback(obj) {
        console.log('eee', obj)
        if (obj.name == 'confirm') {
          app.download(that.data.categorydata.id)
        }
        that.Dialog.CloseDialog();
      }
    })
  },

  mvlook(e){
    wx.navigateTo({
      url: '/pages/weixinlink/weixinlink?url='+e.currentTarget.dataset.url
    })
  },
  mvmin(e){
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.id,
      path: e.currentTarget.dataset.path,
      extraData: {},
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },

  //初始化
  _init() {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    this._getPlayUrl(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    console.log('currentSong',currentSong)
    if (currentSong && currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      manage.stop()
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {
    if(!manage.src){
      wx.playBackgroundAudio({
        dataUrl: currentSong.audioUrl,
        title: currentSong.title,
        coverImgUrl: currentSong.imgUrl
      })
    }
    // 监听音乐播放。
    wx.onBackgroundAudioPlay(() => {
      this.setData({
        play: 2
      })
      app.globalData.play=2
      app.currentSong=currentSong
      app.play(currentSong.id)
    })
    // 监听音乐暂停。
    wx.onBackgroundAudioPause(() => {
      this.setData({
        play: 1
      })
      app.globalData.play=1
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
    })
    // 监听音乐停止。
    wx.onBackgroundAudioStop(() => {
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init()
        return
      }
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
      this.next()
    })
  },
  onTimeUpdate(time){
    // 监听播放拿取播放进度
    if(time){
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration=manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration:this._formatTime(duration),
        percent: currentTime / duration*100
      })
    })
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  getNextIndex(nextFlag) {
    let ret,
        currentIndex = app.globalData.currentIndex,
        mod = this.data.playMod,
        len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    wx.getBackgroundAudioPlayerState({
      success(res) {
        var status = res.status
        if (status == 1) {
          wx.pauseBackgroundAudio()
        } else {
          wx.playBackgroundAudio()
        }
      }
    })
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·栏目',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·栏目',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})